// render-prop 组件的复用

import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

// render - prop 模式

// 创建Mouse组件  要提供自己的状态和方法
class Mouse extends React.Component {
    state = {
        x: 0,
        y: 0
    }
    // 鼠标移动事件的的处理程序
    handleMouseMove = (e) => {
        this.setState({
            x: e.clientX,
            y: e.clientY
        })
    }

    // 监听鼠标移动事件
    componentDidMount() {
        window.addEventListener('mousemove', this.handleMouseMove)
    }

    // 推荐在组件卸载的时候移除掉鼠标事件
    componentWillUnmount() {
        window.removeEventListener('mousemove', this.handleMouseMove)
    }

    render() {
        // return null
        return (
            // this.props.render(this.state),
            // 使用children
            this.props.children(this.state)
        )
    }
}

class App extends React.Component {
    render() {
        return (
            <div>
                <h1>render  props 模式</h1>
                {/* <Mouse render={(mouse)=><p>鼠标位置：{mouse.x}{mouse.y}</p>} /> */}

                {/* 猫捉老鼠 */}
                {/* <Mouse render={
                mouse =>{
                    return (
                        <img src="https://ts1.cn.mm.bing.net/th/id/R-C.193db300d38700a7a909b87caf9967e6?rik=vkFwSbprY2UeHw&riu=http%3a%2f%2fimg.mm4000.com%2ffile%2fe%2fcd%2f4b2ddb2b72.jpg%3fdown&ehk=w%2bnvBGL%2fGdlWz2oP7MA%2bSd5uuFhWBYvEdY9frXUa6BE%3d&risl=&pid=ImgRaw&r=0"
                        alt='猫' style={{width:'50px',height:"50px",position:'absolute',top:mouse.y,left:mouse.x}}></img>
                    )
                }
            } /> */}

                {/* 使用children模式 */}

                <Mouse>
                    {
                        mouse => {
                            return <p>鼠标位置：{mouse.x}{mouse.y}</p>
                        }
                    }
                </Mouse>
            </div>
        )
    }
}

Mouse.propTypes = {
    children: PropTypes.func.isRequired
}

ReactDOM.render(<App />, document.getElementById('root'))